package starpay

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/starpay/starpay"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/starpay/starpay/types"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Starpay{
		MerchantId: config.MerchantId,
		SecretKey:  config.SecretKey,
		Url:        config.Url,
	}
}

type Starpay struct {
	MerchantId string
	SecretKey  string
	Url        string
}
type WithdrawBackData struct {
	MerchantRef  string `json:"merchant_ref"`  // 商户订单号
	SystemRef    string `json:"system_ref"`    // 平台订单号
	Amount       string `json:"amount"`        // 金额
	Fee          string `json:"fee"`           // 手续费
	Status       int    `json:"status"`        // 订单状态：1：Success； 2: Pending；5: Reject
	SuccessTime  int    `json:"success_time"`  // 成功支付时间（时间戳），订单未成功时，该字段值为 null
	ExtendParams string `json:"extend_params"` // 扩展字段

}

// 代收订单创建
func (Star *Starpay) Withdraw(ctx context.Context, req map[string]any) (resp base.WithdrawRes, err error) {
	// 请求第三方接口

	orderNo := req["Order"].(map[string]any)["OrderNo"].(string)
	amount := fmt.Sprintf("%.2f", req["Order"].(map[string]any)["Amount"])
	address := req["Order"].(map[string]any)["UserUsdtWallets"].(map[string]any)["Address"].(string)
	draw, err := starpay.StarWithDraw(Star.Url, Star.MerchantId, orderNo, Star.SecretKey, amount, address)
	if err != nil {
		return resp, err
	} else {
		var data types.WithdrawBackData
		err = json.Unmarshal([]byte(draw.Params), &data)
		resp = base.WithdrawRes{
			OrderSn:      data.MerchantRef,
			ThirdOrderSn: data.SystemRef,
		}
		return resp, err
	}

}
